<template>
  <div>
    <Card>
      <div class="p-relative">
        <div @click="refresh" class="p-absolute refresh-btn">
          <Icon size='24' type="md-refresh" />
        </div>
        <div class="flex-box search-area">
         <!--  <div class="flex-item search-btn">
            <Button type="warning" @click='create'>添加教练</Button>
          </div> -->
          <div class="flex-item">
            <Input v-model="searchObj.name" placeholder="请输入教练名称|昵称|联系电话"></Input>
          </div>

          <div class="flex-item search-btn" @click="search">
            <Button type="warning">搜索</Button>
          </div>
          <div class="flex-item search-btn" @click="reset">
            <Button>重置</Button>
          </div>

        </div>
      </div>

      <Table :columns="tableLogOption" :data="data.list" border :no-data-text="loadingText ? loadingText : '暂无数据'" border
        ref="tables" editable search-place="top">
        <template slot-scope="{ row, index }" slot="start_time">
          {{row.start_time}} - {{row.end_time}}
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">
            <Button type='warning' @click="edit(row, index)" size='small'>编辑</Button>
            <Button type='error' @click="del(row, index)" size='small'>删除</Button>

          </div>
        </template>
      </Table>
      <Page class="foot-page" :current='page.current' :total="page.total" :page-size="page.pageSize" show-total
        show-elevator @on-change="changepage"></Page>

    </Card>

    <!-- 添加弹窗 -->
    <Modal v-model="createModal" :title="createTitle" width='900'>

         <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                 <FormItem label="门店" >

                    <Select v-model="formValidate.store_id" style="width:130px" placeholder='请选择门店'>
                        <Option v-for="(item,index) in data.storeList" :value="item.id" :key="index">{{item.name}} </Option>
                  </Select>

                </FormItem>

                <FormItem label="请选择用户" prop="">
                 <Button type="primary" @click='checkUser'>选择</Button>

                </FormItem>
                <FormItem label="教练名称" prop="name">
                  <Input v-model="formValidate.name" placeholder="请输入教练名称"></Input>
                </FormItem>
               <!--   <FormItem label="电话" prop="mobile">
                  <Input v-model="formValidate.mobile" placeholder="请输入适合人群 如： 10~15岁"></Input>
                </FormItem>

                  <FormItem label="课程类别" prop="name">
                  <Input v-model="formValidate.name" placeholder="请输入门店名称"></Input>
                </FormItem> -->

                <FormItem label="简介">
                  <!-- <Input v-model="formValidate.remark" placeholder="请输入门店名称"></Input> -->
                  <textarea   v-model="formValidate.remark"  name="remark"  rows="5" cols="100">{{formValidate.remark}}</textarea>
                </FormItem>

               <!--  <FormItem label="营业时间" prop="time">
                  <TimePicker type="timerange" :disabled-hours="[0,1,2,3,4,5,6,7]" hide-disabled-options
                    v-model="formValidate.time" format="HH:mm" placeholder="请选择营业时间例如:8:00-22:00" style="width: 250px">
                  </TimePicker>

                </FormItem> -->
                <!-- <FormItem label="头像">
                  <Button type="primary" @click="upload('album')">
                    <Icon type="md-add" />
                    上传图片
                  </Button>
                </FormItem>
                <FormItem v-if="prodGroupBasicObj.album_imageArr && prodGroupBasicObj.album_imageArr.length">
                  <div class="action-div" v-for="(item,index) in prodGroupBasicObj.album_imageArr"
                    style="display: inline-block;margin-right: 10px;margin-bottom: 10px;">
                    <div class="action-btn">

                      <span @click="delImg(index)">删除</span>
                    </div>
                    <img :src="item.url" style="width: 70px;height: 70px;border: 1px solid #eeeeee;" />
                  </div>

                </FormItem>
 -->


            </Form>






      <div slot="footer">
        <Button type="warning" @click="save('formValidate')" :disabled="isDisable" :loading="isLoading">保存</Button>
      </div>
    </Modal>


    <Modal v-model="uploadModal" title="图片管理" class="uploadModal-wrap" :closable='isClosable'>
      <!-- 上传组件 -->
      <div>
        <UploadTool :showUpload='showUpload' :optionObj='uploadImgPathList' @getSelectedImgList='getSelectedImgList'>
        </UploadTool>
      </div>
      <div slot="footer">
        <Button @click='cancelUploadModal'>取消</Button>
        <Button type="primary" @click='confirm(uploadType)'>确定</Button>
      </div>
    </Modal>
    <!-- 选择用户弹窗 -->
    <Modal v-model="userModal" title="提示" width="80%">
       <div class="p-relative">
        <!-- <div @click="refresh" class="p-absolute refresh-btn">
          <Icon size='24' type="md-refresh" />
        </div> -->
        <div class="flex-box search-area">

          <div class="flex-item">
            <Input v-model="searchObj.username" placeholder="请输入名称|昵称|联系电话"></Input>
          </div>

          <div class="flex-item search-btn" @click="searchUser">
            <Button type="warning">搜索</Button>
          </div>


        </div>
      </div>
       <Table :columns="userOption" :data="data.userList" border
       :no-data-text="loadingUserText ? loadingUserText : '暂无数据'"
        ref="tables" editable search-place="top" :key="Math.random()">

        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">
            <Button type='warning' @click="checkCoach(row)" size='small'>选择</Button>


          </div>
        </template>
      </Table>



       <Page class="foot-page" :current='page.user_current' :total="page.user_total" :page-size="page.pageSize" show-total
        show-elevator @on-change="changeUserPage"></Page>
    </Modal>

    <!-- 删除弹窗 -->
    <Modal v-model="delModal" title="提示" width="250">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定删除该数据吗？
      </p>
      <div slot="footer">
        <Button @click='delModal=false'>取消</Button>
        <Button type="primary" @click='confirmDel'>确定</Button>
      </div>
    </Modal>



  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  // 接口
  import {
    getList,
    add,
    put,
    del,
    getCoachCardList,
    coachCardAdd,
    coachCardEdit,
    coachCardDel,
    getUser,
    getLogList,
  } from '@/api/product-group/coach'
  import {
    tableOption,
    coachCardOption,
    userOption,
    tableLogOption,
  } from '../../../data/product-group/coach.js'
  import Tables from '_c/tables'
   import {
    permission
  } from '@/config/permission.js'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import {
    quillEditor,
    Quill
  } from 'vue-quill-editor'
  import {
    uploadImgPathList
  } from '@/config/global.js'

  // 上传组件
  import UploadTool from '../../components/uploadTool/uploadTool.vue'
   import ImageResize from 'quill-image-resize-module'

  Quill.register('modules/imageResize', ImageResize);
  export default {
    name: 'tables_page',
    components: {
      Tables,
      quillEditor,
      UploadTool
    },
    created() {
      let _this = this
      this.$nextTick(function() {
        // 权限校验
        // _this.role_add = permission(this.roles, 'coach/add')
        // _this.role_edit = permission(this.roles, 'coach/edit')
        // _this.role_del = permission(this.roles, 'coach/del')

      })
      // console.log(_this.role_add)

      this.getList()
    },
    watch: {

    },
    mounted() {

    },
    computed: {
      ...mapState({
        prodGroupBasicObj: state => state.share.prodGroupBasicObj,
        roles: state => state.user.roles

      }),
    },
    data() {
       // 工具栏配置
      const toolbarOptions = [
        ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
        ['blockquote', 'code-block'], // 引用，代码块

        [{
          header: 1
        }, {
          header: 2
        }], // 标题，键值对的形式；1、2表示字体大小
        [{
          list: 'ordered'
        }, {
          list: 'bullet'
        }], // 列表
        [{
          script: 'sub'
        }, {
          script: 'super'
        }], // 上下标
        [{
          indent: '-1'
        }, {
          indent: '+1'
        }], // 缩进
        [{
          direction: 'rtl'
        }], // 文本方向

        [{
          size: ['small', false, 'large', 'huge']
        }], // 字体大小
        [{
          header: [1, 2, 3, 4, 5, 6, false]
        }], // 几级标题

        [{
          color: []
        }, {
          background: []
        }], // 字体颜色，字体背景颜色
        [{
          font: []
        }], // 字体
        [{
          align: []
        }], // 对齐方式

        ['clean'], // 清除字体样式
        ['image', 'video'] // 上传图片、上传视频
      ]
      let self = this;
      return {
        editorOption: {
          modules: {
            //imageDrop: true,
            imageResize: {
              displayStyles: {
                backgroundColor: "black",
                border: "none",
                color: "white"
              },
              modules: ["Resize", "DisplaySize", "Toolbar"]
            },

            toolbar: {
              container: toolbarOptions, // 工具栏
              handlers: {
                'image': function(val) {
                  console.log(val)
                  if (val) {
                    self.upload('remark')
                    // document.querySelector('.editor-upload').click()

                  } else {
                    this.quill.format('image', false); //禁用quill内部上传图片
                  }

                }

              }
            }
          }
          // some quill options
        },
        // 权限标识
        role_add: false,
        role_edit: false,
        role_del: false,


        // 上传
        // 子组件传递过来
        isClosable: false,
        previewImgModal: false,
        uploadType: '', // 上传按钮判断
        uploadIndex: 0,
        fromChild: {
          selectedImgList: [],
          week_range:'',
        },
        uploadModal: false,
        showUpload: false,
        uploadImgPathList: uploadImgPathList,
        // 上传
        tableOption: tableOption,
        userOption:userOption,
        tableLogOption:tableLogOption,
        userModal:false,
        delId: '',
        data: {
          list: [],
          storeList:[],
        },

        createTitle: '新增课程',
        isAdd: true, // 新增true,修改false
        isDisable: false, // 新增时提交按钮点击状态
        isLoading: false, // 新增时提交按钮loading状态

        loadingText: '',
        loadingUserText:'',
        tableData: [],
        // 查询参数
        searchObj: {
          name: ''

        },
        // 分页
        page: {
          pageSize: 8,
          current: 1,
          total: 0
        },
        uploadList: [],
        // 分页end
        // 弹窗状态
        createModal: false, // 新增，修改弹窗
        delModal: false, // 删除弹窗


        formValidate: {
          name: '',
          class_hour: '',
          estate: 1,
          fit_member: '',
          coach_name: '0',
          cover_image: [],
          album_image: [],
          store_id:'',
          price:0,
          number:'',
          date_range:'',
          week_range:[],
          time_range:'',
          time_range:'',
          remark:'',
          sorter:0,
          is_home:0,

        },

        ruleValidate: {
          name: [{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }],

          store_id: [{
            required: true,
            message: '请选择门店',
            // type: 'array',
            trigger: 'blur'
          }],


        },
        delImgItem: [],
      }
    },
    methods: {
      // 列表数据
      getList() {
        let _this = this
        let params = {
          page: this.page.current,
          size: this.page.size,
          name: this.searchObj.name
        }

        getLogList(params).then(res => {
          // console.log(res)
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.list = result.list
            // _this.data.storeList = result.storeList
            _this.page.total = result.total
            _this.page.pageSize = result.size
          } else {
            let config = {
              content: res.data.message,
              background: true
            }
            _this.$Message.error(config)
          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },
      checkUser(){

        this.userModal = true
        this.getUser()
      },
      getUser(){
        let _this = this
        let params = {
          page: this.page.user_current,
          size: this.page.user_pageSize,
          name: this.searchObj.username
        }

        getUser(params).then(res => {

          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.userList = result.list
            _this.loadingUserText =JSON.stringify(_this.data.userList)

            _this.page.user_total = result.total
            _this.page.user_pageSize = result.size
          } else {
            let config = {
              content: res.data.message,
              background: true
            }
            _this.$Message.error(config)
          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },
      checkCoach(row){
        this.formValidate.user_id = row.id
        this.formValidate.name = row.username
        this.userModal = false;

      },
      checkStore(e){
        console.log(e)
      },

        changeEstate(status){
            this.formValidate.estate = status ? true : false

        },
        changeIsHome(status){
             this.formValidate.is_home = status ? true : false

        },
      //上传图片过大提示
      handleMaxSize(file) {
        let msg = '图片' + file.name + '，超出了允许上传的10M大小'
        this.$Message.error(msg)
      },
      previewImg() {
        this.previewImgModal = true
      },
      delImg(index,type) {
        if(type == 'cover'){
            this.prodGroupBasicObj.cover_image= '';
            this.prodGroupBasicObj.cover_image_file_name = ''
            this.prodGroupBasicObj.cover_image_type = ''
            this.formValidate.cover_image = ''

        }else if(type=='album'){
             this.prodGroupBasicObj.album_imageArr.splice(index, 1);
            this.formValidate.images.splice(index, 1);
        }

      },
      changepage(e) {
        this.page.current = e
        this.getList()
      },
      changeUserPage(e){
         this.page.user_current = e
           this.getUser()
      },
      // 上传
      upload(type, index) {
        // type为上传的类型，‘cover’封面
        this.uploadModal = true
        this.showUpload = true
        this.uploadType = type
        this.uploadIndex = index
      },
      getSelectedImgList(e) {
        this.fromChild.selectedImgList = e
      },
      cancelUploadModal() {
        this.uploadModal = false
        this.showUpload = false
      },
      confirm(type) {
        console.log(type)
        let _this = this
         if (type == 'cover') {
          // 封面
          _this.formValidate.cover_image ='';
          // console.log(this.fromChild.selectedImgList)
          //   let obj = this.prodGroupBasicObj;
          //   obj.cover_image = this.fromChild.selectedImgList.map((res => {
          //     _this.formValidate.cover_image.push(res.path_name);
          //     return {
          //       url: res.url,
          //       extension: res.extension,
          //       file_name: res.path_name
          //     }
          //   }))
          let obj = this.prodGroupBasicObj;
          obj.cover_image = this.fromChild.selectedImgList[0].url;
          obj.cover_image_type = this.fromChild.selectedImgList[0].extension;
          obj.cover_image_file_name = this.fromChild.selectedImgList[0].path_name;
           _this.formValidate.cover_image = this.fromChild.selectedImgList[0].path_name;
           // console.log(_this.formValidate.cover_image)
          // this.setProdGroupBasicObj(obj)
          // console.log(_this.prodGroupBasicObj);
        } else if (type == 'album') {
            _this.formValidate.album_image = [];
            let obj = this.prodGroupBasicObj;
            obj.album_imageArr = this.fromChild.selectedImgList.map((res => {
              _this.formValidate.album_image.push(res.path_name);
              return {
                url: res.url,
                extension: res.extension,
                file_name: res.path_name
              }
            }))
            // console.log( _this.formValidate.album_image)
        }else if(type == 'remark'){

           let quill = this.$refs.myQuillEditor.quill;
          this.fromChild.selectedImgList.forEach(function(cv) {
            let length = quill.selection.savedRange.index
            // 插入图片
            quill.insertEmbed(length, 'image', cv.url)
            //quill.insertEmbed(length, 'video', url)
            // 调整光标到最后
            quill.setSelection(length + 1)

          })
          console.log('remark:', this.fromChild.selectedImgList)
          this.uploadModal = false;
          this.showUpload = false;
        }
        this.uploadModal = false
      },
      // 新增
      create() {
        console.log(this.role_add)
        if (!this.role_add) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.createModal = true

        this.createTitle = '新增教练'
        this.isAdd = true
        this.formValidate = {} // 表单重置
        this.formValidate.estate = 1;
        this.prodGroupBasicObj.album_imageArr = {}
         this.prodGroupBasicObj.cover_image = ''
        this.handleReset('formValidate') // 验证重置
      },
      // 修改
      edit(row) {
        if (!this.role_edit) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.createModal = true
        this.createTitle = '编辑教练'
        this.isAdd = false
        this.formValidate = {} // 表单重置
        this.formValidate = JSON.parse(JSON.stringify(row))
        // console.log(this.formValidate)
        this.prodGroupBasicObj.album_imageArr = this.formValidate.album_imageArr||[]

         this.prodGroupBasicObj.cover_image = this.formValidate.cover_imageArr[0]['url']
        // this.formValidate.cancel_time = this.formValidate.cancel_time.toString()
        this.handleReset('formValidate') // 验证重置
      },

      // 删除
      del(row) {
        if (!this.role_del) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.delId = row.id
        this.delModal = true

        // 删除接口
      },
      confirmDel() {
        let _this = this
        let obj = {
          id: this.delId
        }
        del(obj).then(res => {
          if (res.data.status == 1) {

            _this.delModal = false
            _this.$Message.success('操作成功')
            _this.getList() // 重新刷新数据
          } else {
            _this.delModal = false

          }
        }).catch(function(error) {
          // 异常
          _this.delModal = false
          console.log(error)
        })
      },
      // 刷新
      refresh() {
        this.searchObj = {} // 清空搜索框
        this.getList()
      },
      // 重置
      reset() {
        this.searchObj = {} // 清空搜索框
        this.getList()
      },
      // 查询
      search() {
        this.page.current =1
        this.getList()
      },
      searchUser(){
        this.page.user_current =1
         this.getUser()
      },
      save(name) {

        let _this = this
        console.log(_this.formValidate)
        this.$refs[name].validate((valid) => {
          if (valid) {
            if (_this.isAdd) {
                // console.log(_this.formValidate)
              // 新增\
               // console.log(_this.formValidate.cover_image)
              let obj = {
                      name: _this.formValidate.name,
                      estate: _this.formValidate.estate,
                      cover_image: _this.formValidate.cover_image|| '',
                      user_id:_this.formValidate.user_id,
                      store_id:_this.formValidate.store_id,
                      remark:_this.formValidate.remark


              }

              // 新增接口
              add(obj).then(res => {
                if (res.data.status == 1) {
                  _this.prodGroupBasicObj.album_imageArr = {};
                  _this.createModal = false
                  _this.getList() // 重新刷新数据
                  _this.$Message.success('操作成功')
                } else {
                  _this.createModal = false
                  // axios响应拦截
                }
              }).catch(function(error) {
                // 异常
                _this.createModal = false
                console.log(error)
              })
            } else {
              // 修改

              let obj = {
                    id:_this.formValidate.id,
                      name: _this.formValidate.name,
                      estate: _this.formValidate.estate,
                      cover_image: _this.formValidate.cover_image|| '',
                      user_id:_this.formValidate.user_id,
                      store_id:_this.formValidate.store_id,
                      remark:_this.formValidate.remark
              }

              // 修改接口
              put(obj).then(res => {
                if (res.data.status == 1) {
                  _this.prodGroupBasicObj.album_imageArr = {};
                  _this.createModal = false
                  _this.getList() // 重新刷新数据
                  _this.$Message.success('操作成功')
                } else {

                }
              }).catch(function(error) {
                // 异常
                console.log(error)
              })
            }

          } else {
            this.$Message.error('请输入必填项!')
          }
        })
      },
      handleReset(name) {
        this.$refs[name].resetFields()
      },
       onEditorBlur(quill) {


      },
      onEditorFocus(quill) {


      },
      onEditorReady(quill) {

      },
      onEditorChange({
        quill,
        html,
        text
      }) {

        this.formValidate.remark=this.escapeStringHTML(html)


      },

      escapeStringHTML(str) {
        // 转码
        str = str.replace(/&lt;/g, '<');
        str = str.replace(/&gt;/g, '>');
        return str;
      },

    }

  }
</script>

<style lang="scss">
  @import "./index";
</style>
